package com.xaicode.learn.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/19 0019 22:08
 */
@Slf4j
public class WSTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        log.info("server receive msg: {}", msg.text());

        // reply
        ctx.channel()
                .writeAndFlush(new TextWebSocketFrame(String.format("server time [%s] - msg: %s", LocalDateTime.now(), msg.text())));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // channel id
        log.info("handlerAdded is called with channel id [{}]", ctx.channel().id().asLongText());
        log.info("handlerAdded is called with channel id [{}]", ctx.channel().id().asShortText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        log.info("handlerRemoved is called with channel id [{}]", ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exception cause: {}", cause.getMessage());
        ctx.close();
    }
}
